package dao

import (
	"errors"
	"go-init/lib/config"
	"go-init/lib/db/mysql"
	"time"
	"unsafe"

	jsoniter "github.com/json-iterator/go"
)

var db *mysql.DB

// Init load DB
func Init() {
	if len(config.Config.Database["write"].DSN) == 0 {
		panic(errors.New("请配置数据库"))
	}
	var err error
	db, err = mysql.NewMysql(mysql.Config{
		DSN:     config.Config.Database["write"].DSN[0],
		ReadDSN: config.Config.Database["read"].DSN,
		Active:  100,
		Idle:    100,
	})
	if err != nil {
		panic(err)
	}
}

const (
	formatDateTime = "2006-01-02 15:04:05"
)

type Time struct{}

func (wt *Time) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
	ts := iter.ReadString()
	*((*time.Time)(ptr)), _ = time.ParseInLocation(formatDateTime, ts, time.Local)
}

func (wt *Time) IsEmpty(ptr unsafe.Pointer) bool {
	ts := *((*time.Time)(ptr))
	return ts.UnixNano() == 0
}

func (wt *Time) Encode(ptr unsafe.Pointer, stream *jsoniter.Stream) {
	ts := *((*time.Time)(ptr))
	stream.WriteString(ts.Format(formatDateTime))
}

func registerTypeTimeAsString() {
	jsoniter.RegisterTypeDecoder("time.Time", &Time{})
	jsoniter.RegisterTypeEncoder("time.Time", &Time{})
}

var json = jsoniter.ConfigCompatibleWithStandardLibrary

func init() {
	registerTypeTimeAsString()
}
